import React, { useState } from "react";
import type { MenuProps } from "antd";
import { Breadcrumb, Button, Layout, Menu, theme, Select } from "antd";
import {
    NavLink,
    Outlet,
    useNavigate,
    useLocation,
    matchPath,
} from "react-router-dom";
import { homee } from "../../router/Index";
import useI18n from "../../app/useI18n";
import { useThemeContext } from "../../app/ThemeContext";

const { Header, Content, Footer, Sider } = Layout;

type MenuItem = Required<MenuProps>["items"][number];

const App: React.FC = () => {
    const { t, lang, changeLanguage, getLanguageOptions } = useI18n();

    function getItem(
        label: React.ReactNode,
        key: React.Key,
        children?: MenuItem[]
    ): MenuItem {
        return {
            key,
            children,
            label,
        } as MenuItem;
    }

    const rfdc = (
        arr: { path: string; title: string; children?: any[] }[]
    ): MenuItem[] => {
        const items: MenuItem[] = [];
        arr &&
            arr.forEach((item) => {
                if (item.children) {
                    items.push(
                        getItem(
                            <NavLink to={`${item.path}?title${item.title}`}>
                                {t(item.title)}
                            </NavLink>,
                            item.path,
                            rfdc(item.children)
                        )
                    );
                } else {
                    items.push(
                        getItem(
                            <NavLink to={`${item.path}?title${item.title}`}>
                                {t(item.title)}
                            </NavLink>,
                            item.path
                        )
                    );
                }
            });
        return items;
    };
    const items = rfdc(homee);

    const [collapsed, setCollapsed] = useState(false);
    // 先解构antd的theme
    const {
        token: { colorBgContainer, borderRadiusLG },
    } = theme.useToken();
    // 再解构自定义主题hook，变量名用appTheme避免冲突
    const { theme: appTheme, handleThemeSwitch } = useThemeContext();
    const naviagte = useNavigate();
    const tuichu = () => {
        localStorage.clear();
        naviagte("/login");
    };

    // 自动生成面包屑
    function getBreadcrumbs(pathname: string) {
        const breadcrumbs: { path: string; title: string }[] = [];
        function find(routeList: any[], parentPath = "") {
            for (const route of routeList) {
                const fullPath = route.path;
                if (matchPath({ path: fullPath, end: false }, pathname)) {
                    breadcrumbs.push({ path: fullPath, title: route.title });
                    if (route.children) {
                        find(route.children, fullPath);
                    }
                } else if (route.children) {
                    find(route.children, fullPath);
                }
            }
        }
        find(homee);
        return breadcrumbs;
    }

    const location = useLocation();
    const breadcrumbs = getBreadcrumbs(location.pathname);

    return (
        <Layout
            style={{
                minHeight: "100vh",
                background: "var(--bg-color)",
                color: "var(--text-color)",
            }}
        >
            <Sider
                collapsible
                collapsed={collapsed}
                onCollapse={(value) => setCollapsed(value)}
                style={{
                    background: "var(--bg-color)",
                    color: "var(--text-color)",
                }}
            >
                <div className="demo-logo-vertical" />
                <Menu
                    theme="dark"
                    defaultSelectedKeys={["1"]}
                    mode="inline"
                    items={items}
                    style={{
                        background: "var(--bg-color)",
                        color: "var(--text-color)",
                    }}
                />
            </Sider>
            <Layout>
                <Header
                    style={{
                        padding: 0,
                        background: "var(--header-bg)",
                        color: "var(--text-color)",
                    }}
                >
                    <div
                        style={{
                            display: "flex",
                            justifyContent: "flex-end",
                            alignItems: "center",
                            height: "70px",
                            paddingRight: "32px",
                            gap: "16px",
                        }}
                    >
                        {/* 主题切换按钮 */}
                        <button
                            onClick={(e) => {
                                const rect = (
                                    e.target as HTMLElement
                                ).getBoundingClientRect();
                                handleThemeSwitch({
                                    x: rect.right - 10,
                                    y: rect.top + 10,
                                });
                            }}
                            style={{
                                border: "none",
                                background: "transparent",
                                cursor: "pointer",
                                outline: "none",
                                fontSize: 22,
                                display: "flex",
                                alignItems: "center",
                            }}
                            aria-label={
                                appTheme === "dark"
                                    ? "Switch to light mode"
                                    : "Switch to dark mode"
                            }
                        >
                            {appTheme === "dark" ? (
                                <svg
                                    xmlns="http://www.w3.org/2000/svg"
                                    className="h-6 w-6"
                                    fill="none"
                                    viewBox="0 0 24 24"
                                    stroke="currentColor"
                                >
                                    <path
                                        strokeLinecap="round"
                                        strokeLinejoin="round"
                                        strokeWidth={2}
                                        d="M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z"
                                    />
                                </svg>
                            ) : (
                                <svg
                                    xmlns="http://www.w3.org/2000/svg"
                                    className="h-6 w-6"
                                    fill="none"
                                    viewBox="0 0 24 24"
                                    stroke="currentColor"
                                >
                                    <path
                                        strokeLinecap="round"
                                        strokeLinejoin="round"
                                        strokeWidth={2}
                                        d="M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z"
                                    />
                                </svg>
                            )}
                        </button>
                        {/* 环形遮罩动画 */}
                        {/* The masking and maskRef props are no longer needed as they are handled by useThemeContext */}
                        <Select
                            value={lang}
                            style={{ width: 120 }}
                            onChange={changeLanguage}
                            options={getLanguageOptions()}
                        />
                        <Button onClick={tuichu}>{t("logout")}</Button>
                        <style>{`
              @keyframes circle-reveal {
                0% {
                  transform: translate(50%,-50%) scale(0);
                  opacity: 1;
                }
                80% {
                  opacity: 1;
                }
                100% {
                  transform: translate(50%,-50%) scale(200);
                  opacity: 1;
                }
              }
            `}</style>
                    </div>
                </Header>
                <Content
                    style={{
                        margin: "0 16px",
                        background: "var(--bg-color)",
                        color: "var(--text-color)",
                    }}
                >
                    <Breadcrumb
                        style={{ margin: "16px 0" }}
                        items={breadcrumbs.map((bc) => ({
                            title: t(bc.title),
                        }))}
                    />
                    <div
                        style={{
                            padding: 24,
                            minHeight: 360,
                            background: "var(--card-bg)",
                            borderRadius: borderRadiusLG,
                            color: "var(--text-color)",
                        }}
                    >
                        <Outlet></Outlet>
                    </div>
                </Content>
                <Footer style={{ textAlign: "center" }}>
                    Ant Design ©{new Date().getFullYear()} Created by Ant UED
                </Footer>
            </Layout>
        </Layout>
    );
};

export default App;
